import java.util.ArrayList;
import java.util.List;

import javax.swing.tree.TreeNode;

/*
 * @lc app=leetcode.cn id=501 lang=java
 *
 * [501] 二叉搜索树中的众数
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    List<Integer> ans = new ArrayList<Integer>();
    int base ,count ,maxCount;
    public int[] findMode(TreeNode root) {
        dfs(root);
        int[] t = new int[ans.size()];
        for(int i =0 ;i<ans.size();i++){
            t[i]=ans.get(i);
        }
        return t;
    }

    public void dfs(TreeNode root){
        if(root == null) return;
        dfs(root.left);
        update(root.val);
        dfs(root.right);
    }
    public void update(int x){
        if(base == x){//和base相等则加count
            count++;
        }else{
            count = 1;
            base = x;
        }
        if(count == maxCount){
            ans.add(x);
        }
        if(count > maxCount){
            maxCount = count;
            ans.clear();
            ans.add(x);
        }
    }
}
// @lc code=end

